package cn.fz.relaxation.job.hupu;

import cn.fz.relaxation.common.util.MyUtil;
import cn.fz.relaxation.dao.entity.RealxHotSearchDO;
import cn.fz.relaxation.job.BaseHotSearchJob;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static cn.fz.relaxation.common.enums.HotSearchEnum.HUPU;

@Slf4j
@Component
public class HupuHotSearchJob extends BaseHotSearchJob {
    @Override
    @XxlJob("hupuHotSearchJob")
    protected ReturnT<String> hotSearch(String param) throws IOException {
        log.info("虎扑热搜爬虫任务开始");
        this.resourceCode = HUPU.getCode();
        try {
            String url = "https://bbs.hupu.com/love-hot";
            Document doc = Jsoup.connect(url).get();
            // 元素列表
            Elements elements = doc.select(".p-title");
            for (int i = 0; i < elements.size(); i++) {
                RealxHotSearchDO searchDO = RealxHotSearchDO.builder().hotSearchResource(resourceCode).build();
                // 设置文章标题
                searchDO.setHotSearchTitle(elements.get(i).text().trim());
                // 设置虎扑三方ID
                searchDO.setHotSearchId(MyUtil.getHashId(HUPU.getCode() + searchDO.getHotSearchTitle()));
                // 设置文章连接
                searchDO.setHotSearchUrl("https://bbs.hupu.com/" + doc.select(".p-title").get(i).attr("href"));
                // 设置热搜热度
                searchDO.setHotSearchHeat(doc.select(".post-datum").get(i).text().split("/")[1].trim());
                // 设置热搜作者
                searchDO.setHotSearchAuthor(doc.select(".post-auth").get(i).text());
                //按顺序排名
                searchDO.setHotSearchOrder(i + 1);
                // 添加到集合
                searchDOList.add(searchDO);
            }
            if (CollectionUtils.isEmpty(searchDOList)){
                log.error("没有获取到虎扑热搜数据");
                return ReturnT.SUCCESS;
            }
            this.saveSearchListToDBAndMap();
            log.info("虎扑热搜爬虫任务结束");
        } catch (IOException e) {
            log.error("获取虎扑数据异常", e);
        }
        return ReturnT.SUCCESS;
    }
}
